import { useRequest, useSize } from 'ahooks';
import { Card } from 'antd';
import * as echarts from 'echarts';
import { FC, ReactElement, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';

import { postDriverSafeIndexRadarChartData, postVehicleSafeIndexRadarChartData } from '@/api/safeIndexApi';
import { hexToRgb } from '@/utils/transform';

import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';
import Ostyle from './index.less';

export type SafeIndexRadarChartProps = {
  /** 标题 */
  title: string;
  /** 类型 */
  type: 'driver' | 'vehicle';
};

function checkStatus(status: number) {
  switch (status) {
    case 0:
      return '等于';
    case 1:
      return '高于';
    case 2:
      return '低于';
  }
}

function checkStatusColor(status: number) {
  switch (status) {
    case 0:
      return '#999';
    case 1:
      return '#33CC67';
    case 2:
      return '#FF3B3B';
    default:
      return '#999';
  }
}

const defaultColor = '#ccc';
const defaultBackgroundColor = '#fff';

const SafeIndexRadarChart: FC<SafeIndexRadarChartProps> = ({ title = '安全指数', type }): ReactElement => {
  const chartDom = useRef<HTMLDivElement>(null);
  const myChart = useRef<echarts.EChartsType>();
  const size = useSize(chartDom.current);

  const [searchParams] = useSearchParams();
  const driverId = searchParams.get('driverId') ?? undefined;
  const safetyIndexCarId = searchParams.get('safetyIndexCarId') ?? undefined;

  const [params, setParams] = useState<any>({
    driverId,
    safetyIndexCarId,
  });

  const label = useMemo(() => {
    if (type === 'driver') {
      return '驾驶员';
    } else if (type === 'vehicle') {
      return '车辆';
    }
  }, [type]);

  const indicatorNameList = useMemo(() => {
    return [`${label}自身得分`, '驾驶陋习', '速度相关', '主动安全'];
  }, [type]);

  useEffect(() => {
    if ((!myChart.current || myChart.current.isDisposed()) && chartDom.current) {
      myChart.current = echarts.init(chartDom.current);

      myChart.current.showLoading({
        text: '加载中...',
        color: '#ff6d3b',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.2)',
        zlevel: 0,
      });

      myChart.current.setOption({
        color: ['#f40', '#61BE67'],
        tooltip: {
          borderWidth: 0,
          formatter: (params: { color: string; seriesName: string; value: number[] }) => {
            let str = '<div style="color: #333">';
            str += `<div style="color: #333; font-weight: bold;">${params.seriesName}</div>`;
            params.value.forEach((item, index: number) => {
              str += `<div style="display: flex; justify-content: space-between; align-items: center">
                <div>
                ${indicatorNameList[index]}
                </div> 
                <div style="display: inline-block; text-align: right; padding-left: 16px">
                <span style="font-weight: bold; text-align: right">${item}分</span>
                </div></div>`;
            });
            str += '</div>';
            return str;
          },
        },
        title: {
          left: 'center',
          top: '23.3%',
          textStyle: {
            fontWeight: 'bold',
            fontSize: '48px',
          },

          subtextStyle: {
            rich: {
              label: {
                color: '#333',
                fontWeight: 'bold',
                fontSize: '16px',
              },
              date: {
                color: '#333',
                fontWeight: 400,
                fontSize: '12px',
              },
            },
          },
        },
        radar: {
          radius: '80%',
          triggerEvent: false,
          name: {
            textStyle: {
              color: '#333',
              fontSize: '14',
              align: 'center',
              borderRadius: 3,
              textWrap: true,
              padding: [-28, 0],
            },
          },
          nameGap: '34',
          splitArea: {
            areaStyle: {
              color: 'transparent',
            },
          },
          axisLine: {
            lineStyle: {
              color: '#FFE5E1',
              type: 'dashed',
            },
          },
          splitLine: {
            lineStyle: {
              width: 2,
              color: ['#FFDACB', '#FFDACB', '#FFDACB', '#FFDACB', '#FFDACB', '#FFDACB'],
            },
          },
        },
        series: [
          {
            name: title,
            type: 'radar',
            areaStyle: {
              normal: {
                color: {
                  x: 0,
                  y: 0,
                  x2: 1,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#fff',
                    },
                    {
                      offset: 0.5,
                      color: '#FFDDD0',
                    },
                    {
                      offset: 1,
                      color: '#FF8657',
                    },
                  ],
                },
              },
            },
            symbolSize: 2.5,
            lineStyle: {
              normal: {
                color: '#FF7038',
                width: 1,
              },
            },
          },
        ],
      });
      return () => {
        if (myChart.current && !myChart.current.isDisposed()) {
          echarts.dispose(myChart.current);
        }
      };
    }
  }, []);

  useEffect(() => {
    if (myChart.current) {
      myChart.current.resize();
    }
  }, [size]);

  const cardTitle = <div style={{ textAlign: 'center', paddingTop: 12 }}>{title ?? '--'}</div>;

  const { data } = useRequest(
    async () => {
      if (type === 'driver') {
        return await postDriverSafeIndexRadarChartData(params);
      } else if (type === 'vehicle') {
        return await postVehicleSafeIndexRadarChartData(params);
      }
    },
    {
      onSuccess(res: any) {
        const data = res.data;

        if (myChart.current) {
          myChart.current.setOption({
            title: {
              text: data.safetyIndex ?? '--',
              textStyle: {
                color: data?.gradeColorShape ?? '#999',
              },
              subtext: `{label|${data?.showName ?? '暂无数据'}}\n\n{date|${
                data?.updateTime ? data?.updateTime + '更新' : ''
              }}`,
              subtextStyle: {
                rich: {
                  label: {
                    color: data?.showName ? '#333' : '#666',
                    fontWeight: data?.showName ? 'bold' : 500,
                    fontSize: '16px',
                  },
                  date: {
                    color: '#333',
                    fontWeight: 400,
                    fontSize: '12px',
                  },
                },
              },
            },
            radar: {
              indicator: [
                { name: `${label}自身得分`, max: data?.selfScoreTotal ?? 0 },
                { name: '驾驶陋习', max: data?.badDrivingHabitsScoreTotal ?? 0 },
                { name: '速度相关', max: data?.speedDependentScoreTotal ?? 0 },
                { name: '主动安全', max: data?.activeSafetyScoreTotal ?? 0 },
              ],
              axisName: {
                fontWeight: 'bold',
              },
              axisLine: {
                lineStyle: {
                  color: {
                    x: 0,
                    y: 0,
                    x2: 1,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: hexToRgb(data?.gradeColorShape ?? defaultColor, 0.32),
                      },
                      {
                        offset: 1,
                        color: hexToRgb(data?.gradeColorShape ?? defaultColor, 0),
                      },
                    ],
                  },
                },
              },
              splitLine: {
                lineStyle: {
                  width: 1,
                  color: [
                    hexToRgb(data?.gradeColorShape ?? defaultColor, 0.08),
                    hexToRgb(data?.gradeColorShape ?? defaultColor, 0.16),
                    hexToRgb(data?.gradeColorShape ?? defaultColor, 0.24),
                    hexToRgb(data?.gradeColorShape ?? defaultColor, 0.32),
                    hexToRgb(data?.gradeColorShape ?? defaultColor, 0.4),
                    hexToRgb(data?.gradeColorShape ?? defaultColor, 0.48),
                  ],
                },
              },
            },
            series: [
              {
                data: [
                  {
                    value: [
                      data?.selfScore ?? 0,
                      data?.badDrivingHabitsScore ?? 0,
                      data?.speedDependentScore ?? 0,
                      data?.activeSafetyScore ?? 0,
                    ],
                    areaStyle: {
                      normal: {
                        color: {
                          x: 0,
                          y: 0,
                          x2: 1,
                          y2: 1,
                          colorStops: [
                            {
                              offset: 0,
                              color: hexToRgb(data?.gradeColorShape ?? defaultColor, 0),
                            },
                            {
                              offset: 1,
                              color: hexToRgb(data?.gradeColorShape ?? defaultColor, 1),
                            },
                          ],
                        },
                      },
                    },
                    itemStyle: {
                      normal: {
                        color: data?.gradeColorShape ?? defaultColor,
                      },
                    },
                    lineStyle: {
                      normal: {
                        color: data?.gradeColorShape ?? defaultColor,
                      },
                    },
                    name: title,
                  },
                ],
              },
            ],
          });

          myChart.current.hideLoading();
        }
      },
      refreshDeps: [params],
    },
  );

  const renderStatusIcon = (status: number) => {
    switch (status) {
      case 0:
        // return <CaretUpOutlined style={{ color: '#999' }} />;
        // return <IconFont style={{ color: '#999' }} type="icon-dengyu" />;
        return <span style={{ color: '#999' }}>持平</span>;
      case 1:
        return <CaretUpOutlined style={{ color: '#33CC67' }} />;
      case 2:
        return <CaretDownOutlined style={{ color: '#FF3B3B' }} />;
      case -1:
        return <CaretUpOutlined style={{ color: '#999' }} />;
    }
  };

  return (
    <Card
      title={cardTitle}
      bordered={false}
      headStyle={{
        border: 0,
        fontSize: 18,
        fontWeight: 'bold',
      }}
      bodyStyle={{ paddingTop: 0 }}
    >
      <div className={Ostyle.safe_index_radar_chart}>
        <div
          className={Ostyle.pentagon}
          style={{
            background: `linear-gradient(to bottom right, ${hexToRgb(
              data?.data?.gradeColorBackground ?? defaultBackgroundColor,
              0.08,
            )} 10%, ${hexToRgb(data?.data?.gradeColorBackground ?? defaultBackgroundColor, 0)} 90%)`,
          }}
        ></div>
        <div
          ref={chartDom}
          style={{
            width: 400,
            height: 220,
            margin: 'auto',
          }}
        ></div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center' }}>
        <div>
          <span style={{ color: checkStatusColor(data?.data.peerAverage) }}>
            {data?.data?.peerAverage !== undefined && data?.data?.peerAverage !== null
              ? checkStatus(data?.data?.peerAverage)
              : '--'}
          </span>
          <span>同行平均</span>
        </div>
        <div>
          <span style={{ marginRight: 4 }}>周环比</span>
          {renderStatusIcon(data?.data.week ?? -1)}
          <span style={{ marginLeft: 4, color: '#666' }}>
            {data?.data.weekDifferenceScore !== undefined && data?.data.weekDifferenceScore !== null
              ? data?.data.weekDifferenceScore === 0
                ? ''
                : data?.data.weekDifferenceScore
              : '--'}
          </span>
        </div>
        <div>
          <span style={{ marginRight: 4 }}>月环比</span>
          {renderStatusIcon(data?.data.month ?? -1)}
          <span style={{ marginLeft: 4, color: '#666' }}>
            {data?.data.monthDifferenceScore !== undefined && data?.data.monthDifferenceScore !== null
              ? data?.data.monthDifferenceScore === 0
                ? ''
                : data?.data.monthDifferenceScore
              : '--'}
          </span>
        </div>
      </div>
    </Card>
  );
};

export default SafeIndexRadarChart;
